$(function(){
    ko.bindingHandlers.jqSortableList = {
        init: function(element, valueAccessor, allBindingsAccessor){
            var options = kjq.utils.getOptions(allBindingsAccessor);
            
            var connectClass = options.connectWith;
            var targetList = undefined;
            if(connectClass){
                options.connectWith = '.'.concat(connectClass);
                if(!allBindingsAccessor()){
                    throw 'Target array(targetList) is undefined.';
                }else{
                    targetList = allBindingsAccessor().targetList;
                }
            }
            
            var list = valueAccessor();
            var sortableListId = kjq.utils.getRandomElementId();
            var content = '<ul class="con kjq-sortable-list '.concat(connectClass ? connectClass: '','" id="', sortableListId,'">');
            for (var i = 0; i < list().length; i++) {
                var listElement = 
                '<li class="kjq-sortable-list ui-state-default"><span class="kjq-sortable-list"></span>'
                .concat(list()[i]).concat('</li>');
                content = content.concat(listElement);
            }
            content = content.concat('</ul>');
            content = $(content);
            $(element).append(content);
           
            options.start = function(event, ui) {
                $(this).attr('oldIndex',  $(ui.item[0]).index());
            };
            
            options.stop = function(event, ui){
                console.log($(this).attr("oldIndex"));
                console.log('stop');
            };
           
            options.update = function (event, ui) {
                var newIndex = ko.utils.arrayIndexOf(ui.item.parent().children(), ui.item[0]);
                if (newIndex >= list().length) newIndex = list().length - 1;
                if (newIndex < 0) newIndex = 0;
                
                var tmp = undefined;
                if (ui.sender) {
                    var index = $(ui.sender).attr("oldIndex");
                    tmp = targetList()[index];
                    console.log('sender : '+tmp);
                //list.splice(newIndex, 0, tmp);
                //targetList.splice(index, 1);
                }else{
                    var oldIndex = $(this).attr("oldIndex");
                    tmp = list()[oldIndex];
                    console.log('nie sender : '+tmp);
                //list.splice(oldIndex, 1);
                //list.splice(newIndex, 0, tmp);
                }
            };
            
            options.receive = function(event, ui){
                var oldIndex = $(this).attr("oldIndex");
                if(connectClass){
                    oldIndex = $(ui.sender).attr("oldIndex");
                }
            };
            
            $('#'.concat(sortableListId)).sortable(options).disableSelection();
        }
    };
});